#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/21
# @Author  : LiJun
# @Email   : lijun@tianyancha.com
# @Version : 1.0.0

import threading
import time
from pprint import pprint

import allure

from interface_0718.api.base_api import BaseApi


class Tag(BaseApi):

    @allure.step("获取tag列表")
    def get_tag_list(self):
        """
        获取标签列表
        :return:
        """
        return self.send("GET", f"/tag/list?access_token={self.token}")

    @allure.step("发起增加标签请求")
    def add_tag(self, tag_name: str = None, tag_id: int = None):
        """
        增加标签
        :param tag_name: 标签名字
        :param tag_id: 不指定标签id则自动+1
        :return:
        """
        data = {
            "tagname": f"{time.time()}_{threading.currentThread().name}" if tag_name is None else tag_name,
            "tagid"  : tag_id,
        }
        return self.send("POST", f"/tag/create?access_token={self.token}", json=data)

    @allure.step("发起更新标签请求")
    def update_tag(self, tag_id: int, tag_name: str = None):
        """
        更新标签
        :param tag_id: 标签id
        :param tag_name: 新标签的name
        :return:
        """
        data = {
            "tagid"  : tag_id,
            "tagname": f"{time.time()}_{threading.currentThread().name}" if tag_name is None else tag_name,
        }
        return self.send("POST", f"/tag/update?access_token={self.token}", json=data)

    @allure.step("发起删除标签请求")
    def delete_tag(self, tag_id: int):
        """
        删除标签
        :param tag_id: 标签ID
        :return:
        """
        return self.send("GET", f"/tag/delete?access_token={self.token}&tagid={tag_id}")

    @allure.step("发起获取标签成员请求")
    def get_tag_member(self, tag_id: int):
        """
        获取标签成员
        :param tag_id: 标签id
        :return:
        """
        return self.send("GET", f"/tag/get?access_token={self.token}&tagid={tag_id}")

    @allure.step("判断tag_id是否在列表里")
    def is_in_tag_list(self, tag_id: int):
        tag_list = self.get_tag_list().json().get("taglist")
        for tag in tag_list:
            if tag_id == tag.get('tagid'):
                return True
        return False

    @allure.step("判断tag_name是否在列表里")
    def is_in_tag_names(self, tag_id: int, tag_name: str):
        tag_list = self.get_tag_list().json().get("taglist")
        for tag in tag_list:
            if tag.get("tagid") == tag_id and tag.get("tagname") == tag_name:
                return True
        return False

    @allure.step("随机一个tag_id")
    def random_tag_id(self):
        """
        随机获取一个tag_id
        :return:
        """
        import random
        tag_list = self.get_tag_list().json().get("taglist")
        tag_id_list = [tag['tagid'] for tag in tag_list]
        if tag_id_list:
            return tag_id_list[random.randint(0, len(tag_id_list) - 1)]
        else:
            return False


if __name__ == '__main__':
    tag = Tag()
    pprint(tag.get_tag_list().json())
    pprint(tag.get_tag_member(1).json())
